﻿using System;
using System.IO.IsolatedStorage;

namespace DIS.WindowsPhone.Toolkit
{
    /// <summary>
    /// <para>A helper class for managing the application's settings</para>
    /// <para>This class must be inherited and used to save and retrieve specific settings for the application</para>
    /// </summary>
    public abstract class SettingsManager
    {
        // Our isolated storage settings
        IsolatedStorageSettings isolatedStore;

        public SettingsManager()
        {
            // Get the settings for this application.
            isolatedStore = IsolatedStorageSettings.ApplicationSettings;
        }

        /// <summary>
        /// Update a setting value for our application. If the setting does not
        /// exist, then add the setting.
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        protected bool AddOrUpdateValue(string key, Object value)
        {
            bool valueChanged = false;

            if (!isolatedStore.Contains(key))
            {
                isolatedStore.Add(key, value);
                valueChanged = true;
            }
            // if new value is different, set the new value.
            if (isolatedStore[key] != value)
            {
                isolatedStore[key] = value;
                valueChanged = true;
            }

            return valueChanged;
        }

        /// <summary>
        /// Get the current value of the setting, or if it is not found, set the 
        /// setting to the default setting.
        /// </summary>
        /// <typeparam name="valueType"></typeparam>
        /// <param name="Key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        protected valueType GetValueOrDefault<valueType>(string key, valueType defaultValue)
        {
            valueType value;

            try
            {
                if (!isolatedStore.Contains(key))
                    value = defaultValue;
                else
                    value = (valueType)isolatedStore[key];
            }
            catch (ArgumentException)
            {
                value = defaultValue;
            }

            return value;
        }

        /// <summary>
        /// Save the settings.
        /// </summary>
        protected void Save()
        {
            isolatedStore.Save();
        }
    }
}
